<template>
  <el-card class="w-full pt-[5px]">
    <el-radio-group v-model="searchForm.checkstatus" @change="handleSearch">
      <el-radio-button v-for="item in totalList" :key="item.value" :value="item.value"
        :label="item.name +'('+item.count+')'"></el-radio-button>
    </el-radio-group>
    <el-form :model="searchForm" class="mt-[20px]" label-width="110px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="对冲号" class="mb-[0px]" prop="cwDch">
            <el-input v-model="searchForm.cwDch" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" class="mb-[0px]" prop="projectName">
            <el-input v-model="searchForm.projectName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人" class="mb-[0px]" prop="chargerName">
            <el-input v-model="searchForm.chargerName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen">
              更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-[20px]" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label-width="0">
            <el-input v-model="searchForm.params.minfee" placeholder="最小认领金额" clearable
              style="width: calc(50% - 10px)" />
            <span style="width: 20px; text-align: center">至</span>
            <el-input v-model="searchForm.params.maxfee" placeholder="最大认领金额" clearable
              style="width: calc(50% - 10px)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0">
            <el-input v-model="searchForm.params.minoutfee" placeholder="最小外拨金额" clearable
              style="width: calc(50% - 10px)" />
            <span style="width: 20px; text-align: center">至</span>
            <el-input v-model="searchForm.params.maxoutfee" placeholder="最大外拨金额" clearable
              style="width: calc(50% - 10px)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目分类" prop="projectType">
            <CustomTreeSelect paramsName="项目分类（所有-有级联）" v-model="searchForm.projectType" valueKey="id"
              labelKey="label" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitId">
            <CustomTreeSelect v-model="searchForm.unitId" valueKey="codeColumn" labelKey="valueColumn" :isFetch="false"
              :dataList="unitList" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0">
            <el-input v-model="searchForm.params.minschool" placeholder="最小留校金额" clearable
              style="width: calc(50% - 10px)" />
            <span style="width: 20px; text-align: center">至</span>
            <el-input v-model="searchForm.params.maxschool" placeholder="最大留校金额" clearable
              style="width: calc(50% - 10px)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="45">
            <CommonDateSelect placeholder="认领时间" v-model:beginTime="searchForm.params.beginTime"
              v-model:endTime="searchForm.params.endTime" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" prop="status">
            <CustomTreeSelect placeholder="审核状态" v-model="searchForm.status" valueKey="dictValue" labelKey="dictLabel"
              :isFetch="false" :dataList="checkStatusList" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="handleDelSelect" v-equalRole="['biz_kycgly']">
        <el-icon class="mr-[5px]">
          <DeleteFilled />
        </el-icon>
        删除
      </el-button>
      <el-button @click="handleExport"> <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出 </el-button>
    </div>
    <el-table :data="tableData" class="w-full" stripe row-key="id" ref="tableRef" @sort-change="sortChange">
      <el-table-column v-equalRole="['biz_kycgly']" type="selection" :selectable="checkSelect" width="55" />
      <el-table-column prop="cwDch" label="对冲号" sortable="b.cw_dch" />
      <el-table-column prop="projectName" label="项目名称" sortable="p.name" >
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.projectId)">{{ row.projectName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="chargerName" label="负责人" sortable="p.charger_name" />
      <el-table-column prop="claimFee" width="135" label="认领金额(万元)" sortable="c.claim_fee">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row)">{{ FloatDiv(row.claimFee, 10000) }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="claimDate" label="认领时间" sortable="c.CLAIM_DATE" />
      <el-table-column prop="unitName" label="所属单位" sortable="u.NAME" />
      <el-table-column prop="checkstatus" label="审核状态" sortable="c.checkstatus">
        <template #default="{ row }">
          <span>{{ getStatusText(row.checkstatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="195" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" v-if="editShowflag(row.checkstatus)" plain
            @click="handleEdit(row)"> 编辑 </el-button>
          <el-button type="primary" size="small" plain v-if="row.checkstatus  =='1' ||row.checkstatus  =='2'" @click="handleView(row)"> 查看 </el-button>
          <el-button type="success" size="small" v-equalRole="['biz_kycgly','biz_kyms']" v-if="row.checkstatus  =='1' && row.isAuditor"
            plain @click="handleCheck(row)"> 审核 </el-button>
          <el-button type="warning" size="small" plain v-equalRole="['biz_kyry']" v-if="row.checkstatus == 1" @click="handleCancel(row.processInstanceId)" >撤销</el-button>
          <el-button type="danger" size="small" v-if="row.checkstatus  =='-1' || row.checkstatus  =='3' " plain
            @click="handleDel(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination v-bind="pagination" @update:current-page="currentChange" @update:page-size="sizeChange" />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @save-success="handleSearch" />
  <ViewModal ref="viewModalRef" />
  <CheckModal ref="checkModalRef" @save-success="handleSearch" />
  <ViewProjectModal ref="viewProjectRef" />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import CommonDateSelect from "@/views/fee/components/CommonDateSelect.vue";
import CommonLabel from "@/views/fee/components/CommonLabel.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import EditModal from "./components/EditModal.vue";
import ViewModal from "./components/ViewModal.vue";
import CheckModal from "./components/CheckModal.vue";
import ViewProjectModal from "@/views/project/zx/lxxm/components/ViewModal.vue";
import { getList,delclaim,getTotal } from "@/api/fee/rz/xmrzbl/index.js";
import { cancelProcess } from "@/api/project/common";
import { getCommonData } from "@/api/project/common.js";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { ElMessage, ElMessageBox } from "element-plus";
import { FloatDiv } from "@/utils/pub";
import { exportFile } from "@/api/fee/common.js";
import { downloadFile } from "@/utils/main";
import { getCookie } from "@/utils/auth";
const { proxy } = getCurrentInstance();
const editModalRef = ref();
const viewModalRef = ref();
const checkModalRef = ref();
const viewProjectRef = ref();
const planType = ref("");
const route = useRoute();
const searchFormOpen = ref(false);
const searchFormRef = ref();
const tableRef = ref();
const totalList = ref([]);
const unitList = useCommonFetch("成果归属单位"); //所有单位; 
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const searchForm = ref({
  cwDch: "",
  cwIncomeId: route.query.id || '',
  chargerName: "",
  unitId: [], 
  projectName: "", 
  projectType:[],
  checkstatus:"",
  orderByColumn:"c.CLAIM_DATE",
  isAsc:"descending",
  status:[],
  params:{beginTime: "",endTime: "",maxfee:"",minfee:"",maxschool:"",minschool:"",maxoutfee:"",minoutfee:"",},
});
const getTotalList = async () =>{
  const res = await getTotal({
      ...searchForm.value,
      checkstatus:"",
      projectType: searchForm.value.projectType.join(","),
      unitId: searchForm.value.unitId.join(","),
      status: searchForm.value.status.join(","),
  })
  if(res.code == 200){
    totalList.value = res.data;
  }
}

const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
useTable((pagin) => 
  getList({
      pageNum: pagin.pageNum,
      pageSize: pagin.pageSize,
      ...searchForm.value,
      projectType: searchForm.value.projectType.join(","),
      unitId: searchForm.value.unitId.join(","),
      status: searchForm.value.status.join(","),
    }),
    { getTotalList }
  );

//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.params.beginTime = "";
  searchForm.value.params.endTime = "";
  searchForm.value.params.maxfee = "";
  searchForm.value.params.minfee = "";
  searchForm.value.params.maxschool = "";
  searchForm.value.params.minschool = "";
  searchForm.value.params.maxoutfee = "";
  searchForm.value.params.minoutfee = "";
  handleSearch();
};

const getStatusText = (status) => {
    if (checkStatusList.value.length && status) {
        if (checkStatusList.value.find(item => item.dictValue == status)) {
            return checkStatusList.value.find(item => item.dictValue == status).dictLabel
        } else {
            return ''
        }
    } else {
        return ''
    }
}

//点击编辑
const handleEdit = (row) => {
  editModalRef.value.edit(row);
};

//点击查看
const handleView = (row)=>{
  viewModalRef.value.view(row.id);
}
//删除
const handleDel = (id) => {
  handleDelete(delclaim, [id]);
};

//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  handleDelete(delclaim, ids);
};

//排序
const sortChange =(row)=>{
 searchForm.value.orderByColumn = row.column.sortable;
 searchForm.value.isAsc=row.order;
 handleSearch();
}

onMounted(() => {
  getTotalList();
});

//设置是否禁用复选按钮
const checkSelect= (row)=>{
  if(row.checkstatus =='-1' || row.checkstatus =='3'){
    return true; //可选
  }else {
    return false;//不可选
 }
}
//编辑权限：暂存和不通过可编辑;科研秘书和科研管理员，审核中可编辑
const editShowflag =(status)=>{
  if (status == '-1' || status == '3') {
    return true;
  } else if (status == '1') {
    if (["biz_kycgly", "biz_kyms"].includes(getCookie("role-key"))) {
      return true;
    }
  }
  return false;
}
/** 导出按钮操作 */
const handleExport = () => {
  let params = {...searchForm.value,projectType: searchForm.value.projectType.join(","),
      unitId: searchForm.value.unitId.join(","),
      status: searchForm.value.status.join(","),};
  exportFile('/feemanage/cwincomeclaim/export',params).then((res) => {
    downloadFile(res, `经费认领清单_${new Date().getTime()}.xlsx`);
  }).catch((error) => {
    console.log(error);
  }); 
}

//点击审核
const handleCheck = (row) => {
  checkModalRef.value.check(row.id,row.processInstanceId);
};

//点击撤销
const handleCancel = async (processId) => {
  ElMessageBox.confirm("是否确认撤销？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      proxy.$modal.loading("请稍候...");
      const res = await cancelProcess(processId);
      proxy.$modal.closeLoading();
      if (res.data) {
        ElMessage({ message: "操作成功！", type: "success", });
        handleSearch();
      } else {
        ElMessage({ message: "操作失败！", type: "warning", });
      }
    } catch (error) {
      proxy.$modal.closeLoading();
      console.log(error);
    }
  });
};

//点击项目名称
const handleShow = (id) => {
  viewProjectRef.value.view(id);
};

//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getTotalList();
};
</script>

<style scoped lang="scss"></style>